<?php


namespace App\Http\Controllers\Api;

use App\Constant\CacheConstant;
use App\Services\Business\Interfaces\MyCategoryServiceInterface;
use App\Services\Business\Services\MyCategoryService;
use App\Zesow\Cache\Impl\MyCategoryCache;
use Illuminate\Http\Request;
use App\Services\Business\Models\MyCategory;
use App\Http\Requests\ApiV2\MyCategoryRequest;
use Illuminate\Support\Facades\Auth;
use App\Events\MyCategoryUpdateEvent;



class MyCategoryController extends BaseController
{
    /**
     * @var MyCategoryService
     */
    protected $myCategoryService;

    public function __construct(MyCategoryServiceInterface $myCategoryService)
    {
        $this->myCategoryService = $myCategoryService;
    }



    /**
     * 递归生成无限菜单树形结构
     *
     * @param array $items 菜单数组
     * @param int|null $parentId 父菜单ID
     *
     */

    public function tree(Request $request,MyCategoryCache $myCategoryCache)
    {

        $categories = $myCategoryCache->tree(Auth::id());
        return $this->successData(compact('categories'));

    }


    public function store(MyCategoryRequest $request, MyCategory $myCategory)
    {
        $userId = $this->id();
        $myCategory->fill($request->filldata())->save();
        event( new MyCategoryUpdateEvent($userId));
        return $this->success();

    }

    public function detail($id)
    {
        $category = MyCategory::query()->where('id', $id)->firstOrFail();
        $categories = $category->children()->get()->toArray();

        return $this->successData(compact('category', 'categories'));
    }


    public function update(MyCategoryRequest $request, $id)
    {

        $userId = $this->id();
        try {
            $category = MyCategory::query()->where('id', $id)->firstOrFail();
            $category->fill($request->filldata())->save();
            event( new MyCategoryUpdateEvent($userId));
            return $this->success(__('更新成功'));
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }


    public function delete(Request $request, $id)
    {
        $userId = $this->id();
        if (MyCategory::query()->where('parent_id', $id)->exists()) {
            return $this->error('该分类下存在子分类，无法删除');
        }
        $MyCategory = MyCategory::query()->where('id', $id)->firstOrFail();

        $MyCategory->delete();
        event( new MyCategoryUpdateEvent($userId));

        return $this->success(__('目录删除成功'));
    }





}
